class Invitation < ActiveRecord::Base
  
  stampable

  validates_presence_of     :email
  validates_length_of       :email,    :within => 6..100
  validates_format_of       :email, :with => /(^([^@\s]+)@((?:[-_a-z0-9]+\.)+[a-z]{2,})$)|(^$)/i

  validates_uniqueness_of   :email, :scope => :group_id, :message => 'There is already a pending invitation for this email address.'
  
  validate :not_a_member_yet, :not_self

  belongs_to :group
   
  before_validation :make_codes

  

  def not_self
    errors.add_to_base('Cannot invite yourself!') if self.email == self.creator.email
  end

  def not_a_member_yet
    errors.add_to_base("Already member of this group") unless is_member(self.email) == nil
  end

	def is_member(email)
	  @invitee = User.find_by_email(email)
	  unless(@invitee == nil)
      Membership.find_by_user_id(@invitee.id)
    end
  end

	protected
	
	def make_codes
	  # TO-DO need unique codes for accept and decline - can't base solely on time...
	  self.key = Digest::SHA1.hexdigest( Time.now.to_s.split(//).sort_by {rand}.join )
  end
	
end
